<template>
    <div :style="chartStyle">
        <div ref="charts" :style="{width: forceFit?'100%':width+'px',height: height+'px'}"></div>
    </div>
</template>

<script>
    import '../../../js/chartTheme/shine.js'
    import '../../../js/chartTheme/macarons.js'
    import chartUtil from './util'

    export default {
        data() {
            return {
                chart: null,
                options: {}
            }
        },
        props: {
            keyword: {
                type: String,
                required: true
            },
            forceFit: {
                type: Boolean,
                default: true
            },
            width: {
                type: Number,
                default: 200
            },
            height: {
                type: Number,
                default: 200
            },
            grid: {
                type: Object,
                default() {
                    return {}
                }
            },
            color: {
                type: Array,
                default() {
                    return ['#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3', '#c23531'];
                }
            },
            title: {
                type: String,
                default: ''
            },
            xAxis: {
                type: Array,
                required: true
            },
            yAxis: {
                type: Array,
                required: true
            },
            series: {
                type: Array,
                required: true
            },
            legends: {
                type: Array,
                default() {
                    return [];
                }
            },
            extra: {
                type: Object,
                default() {
                    return {}
                }
            },
            toolbox: {
                type: Array,
                default() {
                    return []
                }
            },
            url: {
                type: String,
                required: true
            },
            param: {
                type: Object,
                default() {
                    return {};
                }
            },
            smooth: {
                type: Boolean,
                default: true
            },
            chartStyle: {
                type: Object,
                default() {
                    return {}
                }
            },
            showDataZoom: {
                type: Boolean,
                default: true
            },
            dataZoomStart: {
                type: Number,
                default: 0
            },
            dataZoomEnd: {
                type: Number,
                default: 100
            },
            setting: {
                type: Object,
                default() {
                    return {areaStyle: {}};
                }
            },
            animation: {
                type: Boolean,
                default: true
            },
            boundaryGap: {
                type: [Boolean, Array],
                default: true
            },
            maxMinPoint: { //点显示
                type: Boolean,
                default: true
            },
            average: {
                type: Boolean,
                default: true
            }
        },
        methods: {
            init() {
                this.chart = this.EChart.init(this.$refs['charts'], this.$store.state.chartTheme);
                this.options = {
                    title: {
                        text: this.title,
                        left: 'center',
                        textStyle: {
                            fontStyle: 'italic'
                        }
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {show: this.toolbox.indexOf('saveAsImage') > -1}
                        },
                        right: 20
                    },
                    grid: this.grid,
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        right: 10,
                        top: 30,
                        bottom: 20,
                        data: this.legends
                    },
                    xAxis: this.xAxis,
                    yAxis: this.yAxis,
                    series: this.series
                };
            },
            render() {
                this.$nextTick(() => {
                    if (!this.chart) {
                        this.init();
                    }
                    this.chart.showLoading();
                    app.ajax.get(this.url, this.param, (res) => {
                        if (res.s === 0) {
                            this.fillChart(res.data);
                        } else {
                            this.$Message.error('数据加载失败：' + res.msg);
                        }
                        this.chart.hideLoading();
                    }, () => {
                        this.chart.hideLoading();
                    });
                });
            },
            fillChart(data) {
                if (this.title === '') {
                    Object.assign(this.options['title'], {text: data.title});
                }

                let series = [];
                let legends = [];
                let _series = data.series ? data.series : this.series;
                if (!_series || _series.length <= 0) {
                    app.log.error("图表[series]获取异常", data);
                } else {
                    _series && _series.forEach((s) => {
                        let __series = Object.assign(s, {
                            name: s.name,
                            data: chartUtil.scatterData(data.xAxis, data[s.name]),
                            type: 'scatter',
                            label: {
                                emphasis: {
                                    show: true,
                                    position: 'left',
                                    textStyle: {
                                        color: '#444',
                                        fontSize: 16
                                    }
                                }
                            },
                        }, this.extra['series'] ? this.extra['series'] : {}, chartUtil.handleSetting(this.setting));
                        if (this.maxMinPoint) __series['markPoint'] = {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        };
                        if (this.average) __series['markLine'] = {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        };
                        series.push(__series);
                        legends.push(s.name);
                    });
                }
                let yAxis = [];
                this.yAxis && this.yAxis.forEach((y) => {
                    if (this.min) yAxis.min = this.min;
                    if (this.max) yAxis.max = this.max;
                    if (y.axisLabel.formatter) {
                        yAxis.push({
                            axisLabel: {
                                formatter: y.axisLabel.formatter
                            }
                        });
                    } else {
                        yAxis.push({
                            axisLabel: {
                                formatter: '{value}'
                            }
                        });
                    }
                });

                // 合并 options
                if (yAxis.length > 0) {
                    for (let i = 0, len = yAxis.length; i < len; i++) {
                        Object.assign(this.options['yAxis'][i], yAxis[i]);
                    }
                }
                if (data.xAxis && data.xAxis.length > 0) {
                    Object.assign(this.options['xAxis'][0], {data: data.xAxis, boundaryGap: this.boundaryGap});
                }
                if (series.length > 0) {
                    // 清空数组
                    this.options['series'].splice(0, this.options['series'].length);
                    for (let j = 0, len = series.length; j < len; j++) {
                        if (this.options['series'].length < series.length) {
                            this.options['series'].push(series[j]);
                        } else {
                            Object.assign(this.options['series'][j], series[j]);
                        }
                    }
                }
                if (legends.length > 0) {
                    Object.assign(this.options['legend'], {data: legends});
                }
                if (this.showDataZoom) {
                    let start = this.dataZoomStart, end = this.dataZoomEnd;
                    this.options['dataZoom'] = chartUtil.getDataZoom({start, end})
                }
                if (this.animate) {
                    let animate = {
                        animationDelay: function (idx) { //动画
                            // 越往后的数据延迟越大
                            return idx * 100;
                        },
                        animationDurationUpdate: function (idx) { //数据跟新时执行
                            return idx * 100;
                        },
                        animationDelayUpdate: function (idx) {
                            return idx * 100
                        },
                        animationEasing: 'elasticOut',
                        animationEasingUpdate: 'elasticOut'
                    }
                    Object.assign(this.options, animate);
                }
                this.chart.setOption(this.options, true);
            }
        }
    }
</script>
